// pages/home/home.js
var shihan = require('../../common/fetch')
var config = require('../../common/config')
var sceneres = {}
var app = getApp()
var sancodeflag = 0;
var winScale = 750 / app.data.deviceInfo.windowWidth
var goodstimer, goodstimer2, goodstimer3, secondstimer;
var leftSelectedIdx = 1; /*左侧选中的行号*/
var homeSelectedIdx = 0;
var currentPage = 1;
var home = 1;
var fans = 0;
var range, range1, usercity, userprovince;
var home_cache = wx.getStorageSync('home_pic_cache');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isoffline: true,
    circular: true,
    currentIndex: 0,
    hasMore: true,
    homehasMore: true,
    showLoading: true,
    backToTop: false, // 返回顶部
    giftbackToTop: false, // 返回顶部
    // recomtabs: ["推荐", "视频", "特惠", "好物", "品类"],
    // navbar: ["震远同", "冯恒大", "金华默香", "张小泉"],
    navbar: [],
    currentTab: 0, // 导航栏切换索引
    currentStoreItem: "0",
    presentindex: 1,
    start: 1,
    homestart: 1,
    count: 11,
    homecount: 5,
    videostart: 1,
    videocount: 20,
    brand_start: 1,
    brand_count: 3,
    brand_flag: true,
    brand_more: true,
    goodthingsflag: true,
    homegoodthingsflag: true,
    homeeventflag: true,
    videolistflag: true,
    goodthings: [],
    homegoodthings: [],
    homeevent: [],
    videolist: [],
    brandselect: [],
    changetime: {},
    leftTabArray: [],
    rightTabArray: '',
    rightbanner: '',
    lineTop: 120,
    dialogflag: true,
    newgoodsarr: [],
    videohasMore: true,
    filterConflag: false,
    currentstrategyItem: 1,
    videomenuflag: false,
    newproductflag: false,
    videosferesh: false,
    videobackToTop: false,
    promotefresh: true,
    defaults: 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
  },
  onLoad: function(options) { //监听页面加载
    var that = this
    usercity = wx.getStorageSync('usercity') || '';
    userprovince = wx.getStorageSync('userprovince') || '';
    that.checknetword(options)
    var windowres = wx.getSystemInfoSync()
    // app.getCity(function() {
    //   wx.setStorageSync('usercity', config.city)
    //   wx.setStorageSync('userprovince', config.province)
    //   if (usercity != config.city) {
    //     that.eventishome();
    //   }
    // })
    wx.setTopBarText({
      text: '世瀚百年，汇聚传统民族优秀品牌，将好物传承给每一个人！'
    })
    var scene;
    if (options.scene) {
      var str = decodeURIComponent(options.scene);
      if (str&&str.indexOf('&') > 0) {
        scene = decodeURIComponent(options.scene).split('&'); //cid||pid=2&to=e&id=123
      } else {
        scene = [str]
      }
    } else {
      if (options.to && options.id) {
        var paramStr;
        if (options.cid || options.cid == '') {
          paramStr = 'cid=' + options.cid + '&to=' + options.to + '&id=' + options.id
        } else if (options.pid) {
          paramStr = 'pid=' + options.pid + '&to=' + options.to + '&id=' + options.id
        }
        scene = paramStr.split('&');
      }
      if (options.fansid) {
        config.partner_id = options.fansid
      } else if (options.pid) {
        config.partner_id = options.pid
      }
    }

    var sceneresjump = {}
    if (scene && scene.length > 0) {
      for (var i = 0; i < scene.length; i++) {
        var str = scene[i].split('=')[0];
        if (str == 'pid') {
          config.partner_id = scene[i].split('=')[1];
        } else if (str == 'cid') {
          config.cid = scene[i].split('=')[1];
        } else {
          sceneres[scene[i].split('=')[0]] = scene[i].split('=')[1]
        }
      }
    }
    console.log(options);
    console.log(sceneres);
    range = 1090 / winScale;
    range1 = 1090 / winScale;
    var animation = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    var animation1 = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation1 = animation1;
    this.setData({
      changetime: {
        videostatus: true
      },
      filterConflag: false,
      currenscrollH: (windowres.windowHeight) * winScale - 160,
      minewinHeight: windowres.windowHeight
    })
    if (home_cache) {
      this.setData({
        homeinfo: home_cache,
        showLoading: false
      })
    } else {
      this.eventishome();
    }
    if (sceneres.to && sceneres.id) {
      if (sceneres.cid) {
        config.cid = sceneres.cid
      } else {
        config.partner_id = sceneres.partner_id
      }
      that.scenejump(sceneres);
      return //兼容已配置的公众号文章，从首页跳转到商品详情，店铺，专题不需要调起登录
    }
    app.wechatSwitch().then(function(wechat_switch) { //是否打开微信授权开关
      app.commonLogin(sceneres, wechat_switch)
    })
  },
  bindload: function (e) {
    console.log(e)
  },
  onGotUserInfo: function(e) { //测试模拟登陆
    app.moniLogin(sceneres, e);
  },
  refreshdata: function() {
    this.onLoad(this.data.offoptions)
    this.onShow()
  },
  checknetword: function(options) {
    var that = this
    wx.getNetworkType({
      success: function(res) { // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        // console.log(res)
        if (res.networkType == 'none') {
          that.setData({
            isoffline: false,
            offoptions: options || ''
          })
          wx.stopPullDownRefresh()
        } else {
          if (that.data.videosferesh) {
            that.setData({
              isoffline: true
            })
          } else {
            that.setData({
              isoffline: true
            })
          }
        }
      }
    })
  },
  immediateUse: function() {
    this.animation.translateY(range).step();
    this.setData({
      filterConflag: false,
      animationData: this.animation.export()
    })
  },
  closecoupon: function() {
    this.animation.translateY(range).step();
    this.setData({
      filterConflag: false,
      animationData: this.animation.export()
    })
  },
  // 送礼首页点击事件
  opengiftscene: function(e) {
    wx.navigateTo({
      url: '/pages/other/giftscene/giftscene?sceneid=' + e.currentTarget.dataset.id + '&index=' + e.currentTarget.dataset.index
    })
  },
  morestrategy: function() {
    wx.navigateTo({
      url: '/pages/other/giftstrategy/giftstrategy',
    })
  },
  openstrategyinfo: function(e) {
    if (e.currentTarget.dataset.url) {
      var advertname = e.currentTarget.dataset.name || ''
      wx.navigateTo({
        url: '/pages/strategyinfo/strategyinfo?url=' + encodeURIComponent(e.currentTarget.dataset.url) + '&name=' + advertname
      })
    }
  },
  searchByTag: function(e) {
    wx.navigateTo({
      url: '/pages/search/search?tag=' + e.currentTarget.dataset.keyword
    })
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  onShow: function() { //监听页面显示
    var that = this
    if (this.data.promotefresh) {
      this.publicinfo();
    }
    this.checknetword(this.data.offoptions)
  },
  switchrefresh: function(index) {
    // wx.showModal({
    //   title: "提示",
    //   content: index + '索引&&视频' + that.data.videomenuflag + '&&特惠' + that.data.newproductflag,
    //   confirmText: "确认",
    //   confirmColor: "#c40000",
    //   showCancel: true
    // })
    var that = this; //videomenuflag   newproductflag
    if (that.data.videomenuflag) { //视频打开
      if (that.data.newproductflag) { //特惠打开
        switch (Number(index)) {
          case 0:
            if (that.data.homeinfo) {
              that.setData({
                homestart: 1,
                homecount: 5,
                homeevent: []
              });
              this.eventishome();
            }
            break; //推荐
          case 1:
            this.setData({
              showLoading: true,
              videostart: 1,
              searchKeyword: '',
              videolist: []
            });
            that.videolist()
            break; //视频
          case 2:
            if (that.data.newgoods) {
              that.preferask()
            }
            break; //特惠
          case 3:
            that.goodthingask()
            break; //礼物
          case 4:
            if (that.data.rightTabArray) {
              that.categoryask()
            }
            break; //品类
        }
      } else { //特惠关闭
        switch (Number(index)) {
          case 0:
            if (that.data.homeinfo) {
              that.setData({
                homestart: 1,
                homecount: 5,
                homeevent: []
              });
              this.eventishome();
            }
            break; //推荐
          case 1:
            this.setData({
              showLoading: true,
              videostart: 1,
              searchKeyword: '',
              videolist: []
            });
            that.videolist();
            break; //视频
          case 2:
            that.goodthingask()
            break; //礼物
          case 3:
            if (that.data.rightTabArray) {
              that.categoryask()
            }
            break; //品类
        }
      }
    } else { //视频关闭
      if (that.data.newproductflag) { //特惠打开
        switch (Number(index)) {
          case 0:
            if (that.data.homeinfo) {
              that.setData({
                homestart: 1,
                homecount: 5,
                homeevent: []
              });
              this.eventishome();
            }
            break; //推荐
          case 1:
            if (that.data.newgoods) {
              that.preferask()
            }
            break; //特惠
          case 2:
            that.goodthingask()
            break; //礼物
          case 3:
            if (that.data.rightTabArray) {
              that.categoryask()
            }
            break; //品类
        }
      } else { //特惠关闭
        switch (Number(index)) {
          case 0:
            if (that.data.homeinfo) {
              that.setData({
                homestart: 1,
                homecount: 5,
                homeevent: []
              });
              this.eventishome();
            }
            break; //推荐
          case 1:
            that.goodthingask()
            break; //礼物
          case 2:
            if (that.data.rightTabArray) {
              that.categoryask()
            }
            break; //品类
        }
      }
    }
  },
  goodproductishome: function() {
    var that = this
    shihan.sendRequest(config.good_product_is_home + that.data.homestart + '-' + that.data.homecount + '.html', 'GET', {})
      .then(function(response) {
        // console.log(response)
        if (response.data.code == 0) {
          for (var i = 0; i < response.data.data.sh_items.length; i++) {
            response.data.data.sh_items[i].sh_current = 0
          }
          that.setData({
            homegoodthings: that.data.homegoodthings.concat(response.data.data.sh_items),
            homestart: that.data.homestart + 1,
            homehasMore: true,
            homegoodthingsflag: true
          });
        } else {
          that.setData({
            homehasMore: false,
            homegoodthingsflag: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  eventishome: function() { //推荐专题部分接口请求
    var that = this;
    shihan.sendRequest(config.home + that.data.homestart + '-' + that.data.homecount + '.html', 'GET', {})
      .then(function(response) {
        // console.log(response)
        if (response.data.data && response.data.data.sh_rem_collection) {
          that.setData({
            homeeventlen: response.data.data.sh_rem_collection.sh_total_rows
          })
        }
        if (that.data.homeevent.length <= that.data.homeeventlen) {
          if (response.data.code == 0) {
            if (that.data.homestart == 1) {
              if (response.data.data.sh_special_arr&&response.data.data.sh_special_arr.sh_products.length >= 5) {
                response.data.data.sh_special_arr.sh_products = response.data.data.sh_special_arr.sh_products.slice(0, 5);
                response.data.data.sh_special_arr.sh_products = response.data.data.sh_special_arr.sh_products.concat({
                  sh_image: "https://img-oss.shihanbainian.com/upload_dev/images/8/3/5/835d5d3d9be5d0f4a8155ed324509cfa.png",
                  sh_name: "查看更多",
                  sh_id: 'preference'
                })
              }
              that.setData({
                homeinfo: response.data.data,
                showLoading: false
              });
              config.sh_is_partner = response.data.data.sh_is_partner;
              config.sh_search_keyword = response.data.data.sh_search_keyword;
              if (response.data.data.sh_seconds_activity.sh_products.length > 0) {
                var prolen = response.data.data.sh_seconds_activity.sh_products
                var secondgoodstime = {}
                secondgoodstime['sh_start_time'] = prolen[0].sh_start_time
                secondgoodstime['sh_end_time'] = prolen[0].sh_end_time
                clearInterval(secondstimer);
                secondstimer = setInterval(function () {
                  that.timeCalculation(secondgoodstime);
                }, 1000);
              }
            }
            that.setData({
              homeevent: that.data.homeevent.concat(response.data.data.sh_rem_collection.sh_collections),
              homestart: that.data.homestart + 1,
              homehasMore: true,
              homeeventflag: true
            });
          }
        }
        if (that.data.homeevent.length == that.data.homeeventlen) {
          that.setData({
            homehasMore: false,
            homeeventflag: false
          })
        }
        wx.setStorageSync('home_pic_cache', response.data.data);
      }, function(error) {
        that.setData({
          showLoading: false
        });
        console.log(error);
      });
  },
  homeloadMoreData: function() {
    // console.log(this.data.homeeventflag)
    if (this.data.homeeventflag == true) {
      this.setData({
        homeeventflag: false
      })
      this.eventishome();
    }
  },
  videolist: function() { //视频列表部分接口请求
    var that = this;
    shihan.sendRequest(config.video + that.data.videostart + '-' + that.data.videocount + '.html', 'GET', {})
      .then(function(response) {
        // console.log(response)
        if (response.data.code == 0) { //sh_is_show_vote
          that.setData({
            videolistinfo: response.data.data,
            videolist: that.data.videolist.concat(response.data.data.sh_videos),
            videostart: that.data.videostart + 1,
            showLoading: false,
            videolistflag: true,
            videohasMore: true
          });
          clearInterval(goodstimer3);
          goodstimer3 = setInterval(function() {
            shihan.dateformat.call(that, response.data.data);
          }, 1000);
        } else {
          that.setData({
            videohasMore: false,
            showLoading: false,
            videolistflag: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  preferask: function() { //特惠部分接口请求
    var that = this;
    shihan.sendRequest(config.indulgence_banner, 'GET', {}, {})
      .then(function(response) {
        if (response.data.code == 0) {
          that.setData({
            newgoodstop: response.data.data,
          });
          shihan.sendRequest(config.indulgence_goods + that.data.newgoodstop.sh_types[that.data.currentTab].sh_id + '.html', 'GET', {}, {})
            .then(function(response) {
              if (response.data.code == 0) {
                for (var i = 0; i < response.data.data.sh_products.length; i++) {
                  if (response.data.data.sh_products[i].sh_label.sh_location) {
                    var pos = response.data.data.sh_products[i].sh_label
                    pos['posa'] = pos.sh_location.split('_')[0];
                    pos['posb'] = pos.sh_location.split('_')[1];
                  }
                }
                that.setData({
                  newgoods: response.data.data,
                  newgoodstime: response.data.data.sh_event_map,
                  showLoading: false
                });
                clearInterval(goodstimer2);
                goodstimer2 = setInterval(function() {
                  shihan.dateformat.call(that, that.data.newgoodstime);
                }, 1000);
              } else {
                that.setData({
                  showLoading: false
                })
              }
            }, function(error) {
              console.log(error);
            });
        } else {
          that.setData({
            showLoading: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  categoryask: function() { //品类部分接口请求
    var that = this;
    shihan.sendRequest(config.all_category_index, 'GET', {}, {})
      .then(function(response) {
        response.data.data.sh_categorys.unshift({
          sh_id: 0,
          sh_name: "品牌馆"
        });
        var temArray = response.data.data.sh_categorys;
        // console.log(temArray)
        //默认选中第一个
        temArray[0].index = 0;
        for (var i = 1; i < temArray.length; i++) {
          temArray[i].selected = false;
          temArray[i].index = i;
        }
        temArray[that.data.presentindex].selected = true;
        that.setData({
          leftTabArray: temArray,
          showLoading: false
        })
        //再获取第一个栏目对应的右侧列表数据
        if (that.data.presentindex > 0) {
          var temArray = that.data.leftTabArray;
          temArray[1].selected = false; // 取消选中
          temArray[that.data.presentindex].selected = true; // 改变当前选中的行的样式
          that.setData({
            leftTabArray: temArray
          });
        }
        // console.log(response);
      }, function(error) {
        console.log(error);
      });
  },
  loadbrandlist: function(target) { //加载品类右侧品牌列表数据
    var that = this
    shihan.sendRequest(config.brand_all, 'GET', {}, {})
      .then(function(response) {
        if (response.data.code == 0) {
          target.setData({
            rightbrandlist: response.data.data,
            showLoading: false
          });
          var res = wx.getSystemInfoSync()
          target.apHeight = 16;
          target.setData({
            alphabetHeight: res.windowHeight - 160 / (750 / res.windowWidth),
            selectorHeight: 18 * (that.data.rightbrandlist.length)
          })
          target.setData({
            selectorTop: (that.data.alphabetHeight - that.data.selectorHeight) / 2
          })
          target.offsetTop = that.data.selectorTop;
        } else {
          that.setData({
            showLoading: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  leftCellTap: function(e) { //左侧cell的点击事件
    var selectIdx = Number(e.currentTarget.dataset.idx); // 当前选中的行
    if (leftSelectedIdx == selectIdx) { // 如果点击的是已经选中的就不再发送请求
      return;
    }
    var temArray = this.data.leftTabArray;
    temArray[leftSelectedIdx].selected = false; // 取消选中
    leftSelectedIdx = selectIdx; // 记录当前选中的行
    temArray[leftSelectedIdx].selected = true; // 改变当前选中的行的样式
    this.setData({
      leftTabArray: temArray
    });
    //清除右侧数组中的数据
    this.setData({
      rightTabArray: '',
      lineTop: selectIdx * 120,
      alpha: e.currentTarget.id,
      presentindex: selectIdx,
      tableftscroll: ((selectIdx + 1) * 118 - 59 - this.data.minewinHeight / 2) / winScale
    });
    currentPage = 1;
    //重新加载右侧数组中的数据
    if (selectIdx == 0) {
      this.loadbrandlist(this)
    }
  },
  goodthingask: function() { //好物部分接口请求  giftindex  + config.province + '/' + config.city +
    var that = this
    shihan.sendRequest(config.giftindex + config.province + '/' + config.city + '.html', 'GET', {}, {})
      .then(function(response) {
        if (response.data.code == 0) {
          that.setData({
            giftindex: response.data.data,
            showLoading: false
          })
        } else {
          that.setData({
            showLoading: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  sancodefn: function() {
    var that = this
    wx.scanCode({ // 只允许从相机扫码
      onlyFromCamera: true,
      success: (res) => { //res.result == http://www.shihanbainian.com/wx_register.php?cid=2&to=e&id=123
        if (res.result&&res.result.indexOf('http') >= 0) {
          var sceneresult = res.result.split('?')[1].split('&'); //cid=2&to=e&id=123
          var sceneresobj = {}
          for (var i = 0; i < sceneresult.length; i++) {
            sceneresobj[sceneresult[i].split('=')[0]] = sceneresult[i].split('=')[1]
          }
          if (sceneresobj.cid > 0) {
            shihan.sendRequest(config.channel_get, 'POST', {
                channel_id: sceneresobj.cid
              })
              .then(function(response) {
                if (response.data.code == 0) {
                  wx.navigateTo({
                    url: '/pages/other/expensecardbuy/expensecardbuy?channelid=' + sceneresobj.cid
                  })
                } else {
                  wx.showModal({
                    title: "提示",
                    content: response.data.msg,
                    confirmText: "确认",
                    confirmColor: "#c40000",
                    showCancel: false
                  })
                }
              }, function(error) {
                console.log(error);
              });
          }
        } else if (res.result&&res.result.indexOf('bupiao') >= 0) {
          var sceneresult = res.result.split('//')[1]; //bupiao://P20180209105644169
          if (sceneresult) {
            wx.navigateTo({
              url: '/pages/other/recharge/recharge?chargeno=' + sceneresult
            })
          }
        }
      }
    })
  },
  //切换顶部标签
  tabClick: function(e) {
    this.setData({
      start: 1,
      goodthings: []
    })
    this.tabchangefn(e.currentTarget.id)
  },
  tabchangefn: function(a) {
    var selectIdx = Number(a);
    if (homeSelectedIdx == selectIdx) {
      return;
    }
    // wx.showModal({
    //   title: "提示",
    //   content: homeSelectedIdx + '&&' + selectIdx,
    //   confirmText: "确认",
    //   confirmColor: "#c40000",
    //   showCancel: true
    // })
    homeSelectedIdx = selectIdx;
    this.setData({
      currentIndex: a,
      showLoading: true
    });
    var that = this
    if (that.data.videomenuflag) { //视频打开
      if (that.data.newproductflag) { //特惠打开
        switch (Number(a)) {
          case 0:
            this.setData({
              homestart: 1,
              homecount: 5,
              homeevent: []
            });
            this.eventishome();
            break; //推荐
          case 1:
            this.setData({
              showLoading: true,
              videostart: 1,
              searchKeyword: '',
              videolist: []
            });
            this.videolist()
            break; //视频
          case 2:
            this.preferask()
            break; //特惠
          case 3:
            this.goodthingask()
            break; //礼物
          case 4:
            this.categoryask()
            break; //品类
        }
      } else { //特惠关闭
        switch (Number(a)) {
          case 0:
            this.setData({
              homestart: 1,
              homecount: 5,
              homeevent: []
            });
            this.eventishome();
            break; //推荐
          case 1:
            this.setData({
              showLoading: true,
              videostart: 1,
              searchKeyword: '',
              videolist: []
            });
            this.videolist()
            break; //视频
          case 2:
            this.goodthingask()
            break; //礼物
          case 3:
            this.categoryask()
            break; //品类
        }
      }
    } else { //视频关闭
      if (that.data.newproductflag) { //特惠打开
        switch (Number(a)) {
          case 0:
            this.setData({
              homestart: 1,
              homecount: 5,
              homeevent: []
            });
            this.eventishome();
            break; //推荐
          case 1:
            this.preferask()
            break; //特惠
          case 2:
            this.goodthingask()
            break; //礼物
          case 3:
            this.categoryask()
            break; //品类
        }
      } else { //特惠关闭
        switch (Number(a)) {
          case 0:
            this.setData({
              homestart: 1,
              homecount: 5,
              homeevent: []
            });
            this.eventishome();
            break; //推荐
          case 1:
            this.goodthingask()
            break; //礼物
          case 2:
            this.categoryask()
            break; //品类
        }
      }
    }
  },
  publicinfo: function() { //configinfo
    var that = this
    shihan.sendRequest(config.configinfo, 'GET', {})
      .then(function(res) {
        that.setData({
          floatAd: res.data.data.sh_float_ad
        })
        config.video_menu_show = res.data.data.sh_video_menu_show;
        var currentIndex = wx.getStorageSync('currentIndexkey') || homeSelectedIdx;
        if (config.video_menu_show == 0) {
          if (res.data.data.sh_new_product_menu_show == 0) {
            that.setData({
              videomenuflag: false,
              newproductflag: false,
              recomtabs: ["推荐", "礼物", "品类"]
            })
          } else {
            that.setData({
              videomenuflag: false,
              newproductflag: true,
              recomtabs: ["推荐", "特惠", "礼物", "品类"]
            })
          }
        } else {
          if (res.data.data.sh_new_product_menu_show == 0) {
            that.setData({
              videomenuflag: true,
              newproductflag: false,
              recomtabs: ["推荐", res.data.data.sh_video_menu_name, "礼物", "品类"]
            })
          } else {
            that.setData({
              videomenuflag: true,
              newproductflag: true,
              recomtabs: ["推荐", res.data.data.sh_video_menu_name, "特惠", "礼物", "品类"]
            })
          }
        }
        that.setData({
          currentIndex: currentIndex
        })
        that.switchrefresh(that.data.currentIndex)
      }, function(error) {
        console.log(error);
      });
  },
  viewSearch: function() {
    wx.navigateTo({
      url: '/pages/search/search'
    })
  },
  openvideoddetail: function(e) {
    wx.navigateTo({
      url: '/pages/other/videodetail/videodetail?id=' + e.currentTarget.dataset.id
    })
  },
  lookvideorank: function() {
    wx.navigateTo({
      url: '/pages/other/videorank/videorank'
    })
  },
  openvideolist: function() {
    wx.navigateTo({
      url: '/pages/other/videolist/videolist'
    })
  },
  storeChange: function(e) {
    var that = this;
    that.setData({
      currentStoreItem: e.detail.current
    });
  },
  goodthingChange: function(e) {
    var index = e.currentTarget.dataset.index
    this.data.goodthings[index].sh_current = e.detail.current
    this.setData({
      goodthings: this.data.goodthings
    })
  },
  // 滚动计算滚动条距离
  onScroll: function(ev) {
    var scrollTop = ev.detail.scrollTop;
    if (scrollTop > 200) {
      this.setData({
        backToTop: true
      });
    } else {
      this.setData({
        backToTop: false
      });
    }
  },
  videoonScroll: function(ev) {
    var videoscrollTop = ev.detail.scrollTop;
    if (videoscrollTop > 200) {
      this.setData({
        videobackToTop: true
      });
    } else {
      this.setData({
        videobackToTop: false
      });
    }
  },
  giftonScroll: function(ev) {
    var giftscrollTop = ev.detail.scrollTop;
    if (giftscrollTop > 200) {
      this.setData({
        giftbackToTop: true
      });
    } else {
      this.setData({
        giftbackToTop: false
      });
    }
  },
  // 返回顶部
  onBackToTop: function() {
    this.setData({
      backToTop: false,
      scrollTop: 0
    })
  },
  onvideoBackToTop: function() {
    this.setData({
      videobackToTop: false,
      videoscrollTop: 0
    })
  },
  ongiftBackToTop: function() {
    this.setData({
      giftbackToTop: false,
      giftscrollTop: 0
    })
  },
  onNavbarTap: function(e) {
    // console.log(e)
    var that = this;
    this.setData({
      navbarleft: ((e.currentTarget.dataset.index + 1) * 200 - 50 - 375) / winScale,
      currentTab: e.currentTarget.dataset.index,
      currentgoodid: e.currentTarget.dataset.goodid
    });
    shihan.sendRequest(config.indulgence_banner, 'GET', {}, {})
      .then(function(response) {
        that.setData({
          newgoodsBanner: response.data.data.sh_ads,
          navbar: response.data.data.sh_types
        });
        shihan.sendRequest(config.indulgence_goods + that.data.currentgoodid + '.html', 'GET', {}, {})
          .then(function(response) {
            that.setData({
              newgoods: response.data.data,
              newgoodstime: response.data.data.sh_event_map
            });
            clearInterval(goodstimer);
            goodstimer = setInterval(function() {
              shihan.dateformat.call(that, that.data.newgoodstime);
            }, 1000);
            // console.log(response.data.data);
          }, function(error) {
            console.log(error);
          });
      }, function(error) {
        console.log(error);
      });
  },
  loadMoreData: function() {
    var that = this
    if (that.data.goodthingsflag) {
      that.setData({
        goodthingsflag: false
      })
      shihan.sendRequest(config.good_product + that.data.start + '-' + that.data.count + '.html', 'GET', {}, {})
        .then(function(response) {
          if (response.data.code == 0) {
            for (var i = 0; i < response.data.data.sh_items.length; i++) {
              response.data.data.sh_items[i].sh_current = 0
              if (response.data.data.sh_items[i].sh_type == 2) {
                that.setData({
                  newgoodsarr: that.data.newgoodsarr.concat(response.data.data.sh_items[i].sh_id)
                })
              }
            }
            that.setData({
              goodthingslabel: response.data.data,
              goodthings: that.data.goodthings.concat(response.data.data.sh_items),
              start: that.data.start + 1,
              goodthingsflag: true
            })
          } else {
            that.setData({
              hasMore: false,
            })
          }
        }, function(error) {
          console.log(error);
        });
      // console.log(that.data)
    }
  },
  searchvideolist: function() {
    var that = this
    // console.log(that.data.searchKeyword)
    shihan.sendRequest(config.videosearch + that.data.searchKeyword + '/' + that.data.videostart + '-' + that.data.videocount + '.html', 'GET', {}, {})
      .then(function(response) {
        if (response.data.code == 0 && response.data.data.sh_items.length > 0) {
          that.setData({
            videostart: that.data.videostart + 1,
            videolist: that.data.videolist.concat(response.data.data.sh_items),
            videolistflag: true,
            showLoading: false
          })
        } else {
          that.setData({
            showLoading: false,
            videohasMore: false,
            videolistflag: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  loadMoreVideo: function() {
    if (this.data.videolistflag) {
      this.setData({
        videolistflag: false
      })
      if (this.data.searchKeyword) {
        this.searchvideolist()
      } else {
        this.videolist()
      }
    }
  }, //videosearch
  onSearchInput: function(ev) {
    this.setData({
      searchKeyword: ev.detail.value
    });
  },
  onSearchConfirm: function() {
    this.setData({
      videostart: 1,
      videolist: [],
      showLoading: true,
      videolistflag: true
    })
    if (this.data.videolist.length == 0) {
      if (this.data.searchKeyword) {
        this.searchvideolist()
      } else {
        this.videolist()
      }
    }
  },
  timeCalculation: function(staretime) { //sh_create_at:"2017-08-28 16:23:26" 秒杀时间计算
    var that = this
    var time1 = new Date().getTime();
    var time2 = new Date(staretime.sh_start_time.replace(/-/g, '/'));
    var time3 = new Date(staretime.sh_end_time.replace(/-/g, '/'));

    if ((time1 - time2 > 0) && (time3 - time1 > 0)) { //正在进行中
      var micro_second = time3 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      that.setData({
        secondflag: true,
        activitynumer: 1,
        activitytitle: '抢购中',
        secondHour: hour,
        secondMinute: minute,
        secondSecond: second
      })
    } else if ((time1 - time2 < 0) && (time1 - time3 < 0)) { //即将开始 activitytime: '',
      var micro_second = time2 - time1;

      var time = micro_second / 1000;
      // 小时位
      var hour = Math.floor(time / 3600);
      hour = hour <= 9 ? '0' + hour : hour;
      // 分钟位
      var minute = Math.floor(time % 3600 / 60);
      minute = minute <= 9 ? '0' + minute : minute;
      // 秒数
      var second = Math.floor(time % 3600 % 60);
      second = second <= 9 ? '0' + second : second;
      that.setData({
        secondflag: true,
        activitynumer: 2,
        activitytitle: '即将开始',
        secondHour: hour,
        secondMinute: minute,
        secondSecond: second
      })
      // that.setData({
      //   activitytitle: '即将开始',
      //   activityinfo: '限时限量  不容错过'
      // })
      // that.friendlydate(staretime)
    } else {
      that.setData({
        secondflag: false
      })
      clearInterval(secondstimer);
    }
  },
  friendlytime: function(staretime) {
    var time1 = new Date().getTime();
    var time2 = new Date(staretime.sh_start_time.replace(/-/g, '/'));
    var time3 = new Date(staretime.sh_end_time.replace(/-/g, '/'));
    if ((time1 - time2 < 0) && (time1 - time3 < 0)) { //有下一场，未开始 2017-08-28 17:24:40
      var micro_second = time3 - time1;
      var time = micro_second / 1000;
      var day = Math.floor(time / 86400);
      var a = staretime.sh_start_time.split('')[1].split(':')
      if (day == 0) {
        this.setData({
          activityinfo: '下一场明天' + a[0] + ':' + a[1] + '开抢'
        })
      } else if (1 < day < 2) {
        this.setData({
          activityinfo: '下一场明天' + a[0] + ':' + a[1] + '开抢'
        })
      } else if (2 < day < 3) {
        this.setData({
          activityinfo: '下一场后天' + a[0] + ':' + a[1] + '开抢'
        })
      }
    }
  },
  friendlydate: function(staretime) {
    var time1 = new Date().getTime();
    var time2 = new Date(staretime.sh_start_time.replace(/-/g, '/'));
    var time3 = new Date(staretime.sh_end_time.replace(/-/g, '/'));
    if ((time1 - time2 < 0) && (time1 - time3 < 0)) { //即将开始 2017-08-28 17:24:40
      var micro_second = time3 - time1;
      var time = micro_second / 1000;
      var day = Math.floor(time / 86400);
      var a = staretime.sh_start_time.split('')[1].split(':')
      if (day == 0) {
        this.setData({
          activitytime: '明天' + a[0] + ':' + a[1] + '开抢'
        })
      } else if (1 < day < 2) {
        this.setData({
          activitytime: '明天' + a[0] + ':' + a[1] + '开抢'
        })
      } else if (2 < day < 3) {
        this.setData({
          activitytime: '后天' + a[0] + ':' + a[1] + '开抢'
        })
      }
    }
  },
  openPreference: function () {
    wx.navigateTo({
      url: '/pages/other/preference/preference'
    })
  },
  allBrand: function() {
    wx.navigateTo({
      url: '/pages/other/brand/brand'
    })
  },
  opengoodsdetail: function(e) {
    var id = e.currentTarget.dataset.id;
    if (id == 'preference') {//跳转到限时特惠列表页面
      wx.navigateTo({
        url: '/pages/other/preference/preference'
      })
    } else {
      wx.navigateTo({
        url: '/pages/goodsdetail/goodsdetail?goodsid=' + id
      })
    }
  },
  openstoredetail: function(e) {
    if (e.currentTarget.dataset.id) {
      wx.navigateTo({
        url: '/pages/storedetail/storedetail?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type
      })
    } else {
      this.allBrand()
    }
  },
  opensecondgoods: function(e) { //打开秒杀详情
    var tit = e.currentTarget.dataset.tit || ''
    var sharetit = e.currentTarget.dataset.sharetit || ''
    var shareimg = e.currentTarget.dataset.shareimg || ''
    var shareurl = e.currentTarget.dataset.url || ''
    wx.navigateTo({
      url: '/pages/secondactivity/secondactivity?tit=' + tit + '&sharetit=' + sharetit + '&shareimg=' + shareimg + '&shareurl=' + encodeURIComponent(shareurl)
    })
  },
  openthemedetail: function(e) {
    var url = e.currentTarget.dataset.url
    var target = e.currentTarget.dataset.target
    var targetval = e.currentTarget.dataset.targetval
    var advertname = e.currentTarget.dataset.name || ''
    if (target == 'seller') {
      wx.navigateTo({
        url: '/pages/storedetail/storedetail?id=' + targetval + '&type=' + e.currentTarget.dataset.target
      })
    } else if (target == 'product') {
      wx.navigateTo({
        url: '/pages/goodsdetail/goodsdetail?goodsid=' + targetval
      })
    } else {
      if (url&&url.indexOf('https://') == 0) {
        wx.navigateTo({
          url: '/pages/strategyinfo/strategyinfo?url=' + encodeURIComponent(url) + '&name=' + advertname
        })
      }
    }
  },
  jumpadvert: function(e) { //广告位跳转
    app.AdSkipper(e)
  },
  scenejump: function(param) {
    if (param.to) {
      var scenetype = param.to
      var sceneid = param.id
      console.log(param)
      switch (String(scenetype)) {
        case 'p':
          wx.navigateTo({
            url: '/pages/goodsdetail/goodsdetail?goodsid=' + sceneid
          })
          break; //商品详情
        case 's':
          wx.navigateTo({
            url: '/pages/storedetail/storedetail?id=' + sceneid
          })
          break; //店铺主页
        case 'e':
          wx.navigateTo({
            url: '/pages/strategyinfo/strategyinfo?url=' + encodeURIComponent(config.commonurl + 'h5/event.html?target_id=' + sceneid)
          })
          break; //专题详情
      }
    }
  },
  opencategory: function() {
    if (this.data.videomenuflag) { //视频打开
      if (this.data.newproductflag) { //特惠打开
        this.tabchangefn(4)
      } else { //特惠关闭
        this.tabchangefn(3)
      }
    } else { //视频关闭
      if (this.data.newproductflag) { //特惠打开
        this.tabchangefn(3)
      } else { //特惠关闭
        this.tabchangefn(2)
      }
    }
  },
  opencategorydetail: function(e) {
    wx.navigateTo({
      url: '/pages/categoryDetail/categoryDetail?type=' + e.currentTarget.dataset.type + '&topcid=' + e.currentTarget.dataset.topcid + '&cid=' + e.currentTarget.dataset.cid + '&bid=' + e.currentTarget.dataset.bid
    })
    // let t = setTimeout(function() {
    //   app.isNavigating = false;
    //   clearTimeout(t);
    // }, 500);
    // if (!app.isNavigating) {
    //   app.isNavigating = true;
    //   wx.navigateTo({
    //     url: '/pages/categoryDetail/categoryDetail?brandid=' + e.currentTarget.dataset.brandid + '&cid=' + e.currentTarget.dataset.cid
    //   })
    // }
  },
  handlerAlphaTap(e) {
    let {
      ap
    } = e.target.dataset;
    this.setData({
      alphalist: ap
    });
  },
  handlerMove(e) {
    var list = this.data.rightbrandlist;
    let moveY = e.touches[0].clientY;
    let rY = moveY - this.offsetTop;
    if (rY >= 0) {
      let index = Math.ceil((rY - this.apHeight) / this.apHeight);
      if (0 <= index < list.length) {
        let nonwAp = list[index];
        nonwAp && this.setData({
          alphalist: nonwAp.sh_zimu
        });
      }
    }
  },
  onHide: function() {
    clearInterval(goodstimer);
    clearInterval(goodstimer2);
    clearInterval(goodstimer3);
    clearInterval(secondstimer);
    wx.removeStorageSync('currentIndexkey')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(goodstimer);
    clearInterval(goodstimer2);
    clearInterval(goodstimer3);
    clearInterval(secondstimer);
    wx.removeStorageSync('currentIndexkey')
  },
  onPullDownRefresh: function() { //监听用户下拉动作
    console.log('下拉刷新')
  },
  onReachBottom: function() { //页面上拉触底事件的处理函数

  },
  onShareAppMessage: function() { //用户点击右上角分享
    var shareurl;
    var customerId = wx.getStorageSync('customerId') || ''
    shareurl = '/pages/home/home?pid=' + customerId
    return {
      title: '世瀚百年，汇聚传统民族优秀品牌，将好物传承给每一个人',
      path: shareurl,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
})